import { fabric } from 'fabric';

class Brush extends fabric.PencilBrush {
  constructor(canvas, options = {}) {
    // 必须先传入 canvas
    super(canvas);

    const defaultOptions = {
      width: 2, // 画笔宽度
      color: '#000000', // 画笔颜色
      strokeLineCap: 'round', // 线条端点样式
      strokeLineJoin: 'round', // 线条连接处样式
    };

    // 合并默认选项和传入的选项
    this.options = {
      ...defaultOptions,
      ...options,
    };

    // 设置画笔属性
    this.color = this.options.color;
    this.width = this.options.width;
    this.strokeLineCap = this.options.strokeLineCap;
    this.strokeLineJoin = this.options.strokeLineJoin;

    // 存储绘制的路径
    this.paths = [];

    // 绑定事件处理
    this._bindEvents();
  }

  // 绑定画布事件
  _bindEvents() {
    // 在路径创建完成时的处理
    this.canvas.on('path:created', (e) => {
      const path = e.path;
      // 将创建的路径添加到数组中
      this.paths.push(path);
      // 设置路径的属性
      path.set({
        stroke: this.color,
        strokeWidth: this.width,
        strokeLineCap: this.strokeLineCap,
        strokeLineJoin: this.strokeLineJoin,
        selectable: true, // 允许选择
        hasControls: true, // 显示控制点
        cornerSize: 10,
        transparentCorners: false,
        cornerColor: this.color,
        borderColor: this.color,
        id: '',  // 添加id属性
      });
      this.canvas.requestRenderAll();
    });
  }

  // 开始绘制
  start() {
    this.canvas.isDrawingMode = true;
    this.canvas.freeDrawingBrush = this;
    return this;
  }

  // 停止绘制
  stop() {
    this.canvas.isDrawingMode = false;
    return this;
  }

  // 更新属性
  updateProps(props) {
    if (props.color) {
      this.color = props.color;
    }
    if (props.width) {
      this.width = props.width;
    }
    if (props.strokeLineCap) {
      this.strokeLineCap = props.strokeLineCap;
    }
    if (props.strokeLineJoin) {
      this.strokeLineJoin = props.strokeLineJoin;
    }
    return this;
  }

  // 清除所有绘制的路径
  clear() {
    this.paths.forEach((path) => {
      this.canvas.remove(path);
    });
    this.paths = [];
    this.canvas.requestRenderAll();
    return this;
  }

  // 撤销最后一笔
  undo() {
    const lastPath = this.paths.pop();
    if (lastPath) {
      this.canvas.remove(lastPath);
      this.canvas.requestRenderAll();
    }
    return this;
  }

  // 将所有路径移到顶层
  bringToFront() {
    this.paths.forEach((path) => {
      this.canvas.bringToFront(path);
    });
    this.canvas.requestRenderAll();
    return this;
  }

  // 将所有路径移到底层
  sendToBack() {
    this.paths.forEach((path) => {
      this.canvas.sendToBack(path);
    });
    this.canvas.requestRenderAll();
    return this;
  }

  // 删除所有路径
  remove() {
    this.clear();
    this.stop();
  }
}

export default Brush;
